package web;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * 登录检查过滤器,用来判断用户是否登录.
 */
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String sp = req.getServletPath();
//        将不需要检查的请求排除
        String[] paths = new String[]{"/toLogin.action","/login.action","/verify.action"};
//        判断当前路径是否为其中之一,若是则请求继续,不再执行后面的判断.
        for(String path:paths){
            if(path.equals(sp)){
                chain.doFilter(req,res);
                return;
            }
        }
//        从session中获取adminCode
        HttpSession session = req.getSession();
        String adminCode = Objects.toString(session.getAttribute("adminCode"));
//        通过adminCode判断用户是否登录
        if(adminCode==null){
//            没登录,重定向到登录页面
            res.sendRedirect(req.getContextPath()+"/toLogin.action");
        }else {
//            已登录,请求继续
            chain.doFilter(req,res);
        }
    }

    @Override
    public void destroy() {

    }
}
